<template>
    <div class="container">
        <el-card style="max-width: 480px; margin: auto; margin-top: 100px;">
            <el-form :model="loginForm" class="login-form" @submit.native.prevent="onSubmit" label-width="auto" style="max-width: 600px">
                <el-form-item label="用户名" :rules="[{ required: true, message: '请输入你的用户名', trigger: 'blur' }]">
                    <el-input v-model="loginForm.username" placeholder="Username"></el-input>
                </el-form-item>
                <el-form-item label="密码" :rules="[{ required: true, message: '请输入你的密码', trigger: 'blur' }]">
                    <el-input v-model="loginForm.password" type="password" placeholder="Password"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onSubmit" style="margin: 0 auto;">登录</el-button>
                    <el-button type="primary" @click="gotoRegister" style="margin: 0 auto;">注册</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>


</template>

<script setup>
import { reactive } from 'vue';
import { login } from "../../api/login.js"
import { setToken, setUsername } from "../../utils/auth.js";
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

const router = useRouter()


const loginForm = reactive({
    username: '',
    password: ''
});

const onSubmit = () => {
    login(loginForm).then(res => {
        setToken(res.data.token);
        setUsername(res.data.username);
        ElMessage({
            message: "登录成功",
            type: 'success',
        })
        router.push('/bikes');
    });
};

const gotoRegister = () => {
    router.push('/register');
}

</script>

<style scoped>
.login-form {
    width: 300px;
    margin: 100px auto;
}

.container {
    height: 100vh;
    width: 100vw;
}
</style>